const bcrypt = require('bcrypt')
const jsonwebtoken = require('jsonwebtoken')
const {secret} = require('./../config/index')
const AsyncMysqljs = require('../mysql/index')
const Get = AsyncMysqljs().get

module.exports = async (ctx, next) => {
    let {username, password} = ctx.request.body
    if(!username || !password) {
        ctx.status = 200;
        ctx.body = {
            code: 0,
            data: {},
            msg: '请输入完整的账号密码！',
        }
        return;
    }
    const sql = 'SELECT * FROM user WHERE username=?'
    const user = await Get(sql,[username])
    
    if(!user) {
        ctx.body = {
            code: 0,
            data: {},
            msg: '没有找到该用户，请注册!',
        }
        return;
    }
    let userToken = {
        name: username,
    }
    const token = jsonwebtoken.sign(userToken, secret, {expiresIn: '2h'});
    if(await bcrypt.compare(password, user.password)) {
        let {password, ...users} = user
        ctx.body = {
            code: 1,
            data: {
                user: users,
                token: token,
            },
            msg: '登录成功！',
        }
    } else {
        ctx.body = {
            code: 0,
            data: {},
            msg: '密码不正确请重新登录',
        }
    }
}